/*
* Node 封装 MongoDB
* */
const path = require('path');
const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')();
const render = require('koa-art-template');
const DB = require('./Utils/db');
const app = new Koa();
app.use(bodyParser());
render(app,{
    root:path.resolve(__dirname, 'Views'),
    extname:'.html',
    debug: process.env.NODE_ENV !== 'production'
});

router.get('/',async (ctx)=>{
    let result = await DB.findDocuments('user',{});
    ctx.render('index',{list:result});
});

router.get('/edit', async (ctx)=>{
    const id = ctx.query.id;
    let result = await DB.findDocuments('user', {"_id":DB.getObjectId(id)});
    ctx.render('edit',{list:result[0]});
});

router.post('/doEdit',async (ctx)=>{
    let params = ctx.request.body;
    await DB.updateDocument(
        'user',
        {'_id': DB.getObjectId(params.id)},
        {name:params.name,age:params.age,sex:params.sex}
    ).then(data=>{
        if(data.result.ok){
            ctx.redirect('/');
        }
    }).catch(err=>{
        console.log(err);
        ctx.redirect('/');
    })
});

router.get('/delete', async (ctx)=>{
    let id = DB.getObjectId(ctx.query.id);
    let data = DB.removeDocument('user',{'_id':id});
    if(data){
        ctx.redirect('/')
    }
});


app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000);

